package hi.doubletracker;

import hi.BooleanListener;
import hi.TrackDataListener;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.InputEvent;

import javax.swing.JPanel;

public class DoubleTrackerPanel extends JPanel implements ComponentListener, TrackDataListener, BooleanListener {
	
	Rectangle mouseRect;
	Dimension inputSpan = new Dimension(640, 480);
	
	int mouseBlobSize = 15;
	
	private boolean controlMouse = true;
	
	private class MouseData {
		
		boolean active;
		int x;
		int y;
		
		MouseData(boolean active, int x, int y) {
			this.active = active;
			this.x = x * mouseRect.width / inputSpan.width + mouseRect.x;
			this.y = y * mouseRect.height / inputSpan.height + mouseRect.y;
		}
	}
	
	MouseData primary = null;
	MouseData secondary = null;
	
	public DoubleTrackerPanel(Rectangle mouseRect) {
		super();
		addComponentListener(this);
		this.mouseRect = mouseRect;
	}
	
	@Override
	public void setState(boolean active, int x, int y) {
		if (controlMouse) {
			//placing cursor
			primary = new MouseData(active, x, y);
			repaint();
		}
	}
	
	@Override
	public void setState(boolean primaryActive, int primaryX, int primaryY,
			boolean secondaryActive, int secondaryX, int secondaryY) {
		if (controlMouse) {
			//placing cursors
			primary = new MouseData(primaryActive, primaryX, primaryY);
			secondary = new MouseData(secondaryActive, secondaryX, secondaryY);
			repaint();
		}
		
	}
	
	protected void paintComponent(Graphics g) { 
	    super.paintComponent(g);
	    drawMouse(g, primary);
	    drawMouse(g, secondary);
	}
	
	private void drawMouse(Graphics g, MouseData mouse) {
	    if (mouse != null) {
	    	if (mouse.active) {
	    		g.setColor(Color.red);
	    	} else	{
	    		g.setColor(Color.darkGray);
	    	}
		    g.fillOval(mouse.x, mouse.y, mouseBlobSize, mouseBlobSize); 
	    }
	}
	
	@Override
	public void componentResized(ComponentEvent e) {
		handleBoundsChange(e);
	}

	@Override
	public void componentMoved(ComponentEvent e) {
		handleBoundsChange(e);
	}
	
	@Override
	public void componentHidden(ComponentEvent arg0) {}

	@Override
	public void componentShown(ComponentEvent arg0) {}
	
	private void handleBoundsChange(ComponentEvent e) {
		Rectangle windowRect = e.getComponent().getBounds();
		mouseRect = windowRect;
	}

	@Override
	public void setActive(boolean active) {
		// TODO Auto-generated method stub
		
	}
}
